<template>
  <div class="page-layout">
    <div class="tabs">
      <el-button v-for="(tab, index) in tabs" :key="index" :type="activeTab === tab.value ? 'primary' : ''" @click="changeTab(tab.value)">
        {{ tab.label }}
      </el-button>
    </div>
    <div class="search time-period-picker select">
      <el-select v-model="searchParams.dateType" placeholder="请选择" style="min-width: 4vw" @change="resetDate">
        <el-option label="日" value="1"></el-option>
        <el-option label="月" value="2"></el-option>
      </el-select>
      <el-date-picker
        v-if="searchParams.dateType === '1'"
        v-model="searchParams.dateRange"
        type="daterange"
        range-separator="至"
        @change="onDateRangeChange"
        value-format="YYYY-MM-DD"
      />
      <el-date-picker
        v-else
        v-model="searchParams.monthRange"
        type="monthrange"
        range-separator="至"
        @change="onMonthRangeChange"
        value-format="YYYY-MM"
      />
    </div>
    <el-divider />
    <el-container>
      <el-header style="height: 25vh">
        <el-radio-group v-model="topRadio" text-color="#626aef" fill="rgb(239, 240, 253)" class="radio-style top-radio-style">
          <el-radio-button label="损失重量" value="weight" />
          <el-radio-button label="损失个数" value="count" />
        </el-radio-group>
        <!-- <graph-line :datax="topDatax" :data1="topRadio === 'weight' ? topWeightData : topCountData" :data-name="[topYAxisName]" /> -->
        <graph-line
          :datax="bottomDatax"
          :data1="topRadio === 'weight' ? bottomWeightLoss : bottomWeightCount"
          :data2="topRadio === 'weight' ? bottomYieldLoss : bottomYieldCount"
          :data3="topRadio === 'weight' ? bottomQualityLoss : bottomQualityCount"
          :title="bottomTitle"
          :data-name="['原料重量不符占比(%)', '成材率占比(%)', '质量占比(%)']"
          :yname="'损失重/生产总重(%)'"
        />
      </el-header>
      <el-main>
        <div class="main-container">
          <div class="item">
            <graph-bar-line :datax="midDatax" :data-bar1="midData" :y-axis-name="['损失重量(吨)']" :bar-name="['损失重量']" />
          </div>
          <div class="item">
            <!-- <el-table
              :data="tableData"
              :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
              :cell-style="{ textAlign: 'center' }"
              height="28vh"
            >
              <el-table-column prop="steelGrade" label="钢种" />
              <el-table-column prop="exthkSpeci" label="厚度分档" />
              <el-table-column prop="widSpeci" label="宽度分档" />
              <el-table-column prop="targetValue" label="目标值" />
              <el-table-column prop="yield" label="成材率" />
            </el-table> -->
            <div class="advice">
              <typing-text v-if="advice" :text="adviceResult" style="height: 100%" />
              <span v-else v-loading="textLoading"></span>
            </div>
          </div>
        </div>
      </el-main>
      <el-footer style="height: 25vh">
        <!-- <el-radio-group v-model="bottomRadio" text-color="#626aef" fill="rgb(239, 240, 253)" class="radio-style bottom-radio-style">
          <el-radio-button label="损失重量" value="weight" />
          <el-radio-button label="损失数量" value="count" />
        </el-radio-group> -->
        <graph-bar-line
          v-if="coilCountGraph.x.length > 0"
          :datax="coilCountGraph.x"
          :data-line1="coilCountGraph.y1"
          :data-line2="coilCountGraph.y2"
          :data-bar1="coilCountGraph.y3"
          :other="coilCountGraph.other"
          :title="'优化建议分卷数与实际分卷数'"
          :line-name="['推荐分卷数', '实际分卷数']"
          :bar-name="['新增费用']"
          :y-axis-name="['分卷个数(卷)', '新增费用(元)']"
        />
        <el-empty v-else></el-empty>
      </el-footer>
    </el-container>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, onUnmounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import GraphBarLine from './GraphBarLine.vue';
  import GraphLine from './GraphLine.vue';
  import dayjs from 'dayjs';
  import { api } from '/@/api/VolumeDivisionOptimization/index';
  import TypingText from './TypingText.vue';

  interface SearchParams {
    dateType: '1' | '2';
    dateRange: [string, string];
    monthRange: [string, string];
    lineName: 'TCM2280' | 'CAL1630' | 'CAL2150' | 'CGL1870' | 'RCL1630' | 'RCL2150' | 'RCL1870';
  }

  interface GraphData {
    x: string[];
    y1: number[];
    y2?: number[];
    y3?: number[];
    y4?: number[];
    other?: any;
  }

  const tabs = [
    { value: 'CAL2150', label: '2#连退' }, // CAL2150连退
    { value: 'CAL1630', label: '3#连退' }, // CAL1630连退
    // { value: 'TCM2280', label: '3#酸轧' }, // TCM2280酸轧
    { value: 'CGL1870', label: '5#镀锌' }, // CGL1870镀锌
    { value: 'RCL2150', label: '4#重卷' }, // CAL2150重卷
    { value: 'RCL1630', label: '5#重卷' }, // CAL1630重卷
    { value: 'RCL1870', label: '6#重卷' }, // CGL1870重卷
  ];
  const activeTab = ref<'TCM2280' | 'CAL1630' | 'CAL2150' | 'CGL1870' | 'RCL1630' | 'RCL2150' | 'RCL1870'>('CAL2150');
  const searchParams = reactive<SearchParams>({
    dateType: '1',
    dateRange: ['', ''],
    monthRange: ['', ''],
    lineName: 'CAL1630',
  });

  const topRadio = ref<'weight' | 'count'>('weight');
  const bottomRadio = ref<'weight' | 'count'>('weight');
  const bottomTitle = computed(() => {
    return bottomRadio.value === 'weight' ? '缺陷原因损失比' : '缺陷数量损失比';
  });
  const midDatax = ref<string[]>([]);
  const midData = ref<any>([]);
  const bottomWeightLoss = ref([]);
  const bottomYieldLoss = ref([]);
  const bottomQualityLoss = ref([]);
  const bottomWeightCount = ref([]);
  const bottomYieldCount = ref([]);
  const bottomQualityCount = ref([]);
  const bottomDatax = ref([]);

  const coilCountGraph = reactive<GraphData>({
    x: [],
    y1: [],
    y2: [],
    y3: [],
    other: [],
  });

  const textLoading = ref(false);
  const advice = ref('');
  const adviceResult = ref('');

  const changeTab = (tabValue: any) => {
    activeTab.value = tabValue;
    searchParams.lineName = tabValue;
    onSearch();
  };

  const onDateRangeChange = (val: any) => {
    // 处理清空选择的情况
    if (!val || val.length < 2) {
      searchParams.dateRange = val;
      onSearch();
      return;
    }

    const [startStr, endStr] = val;
    const startTime = new Date(startStr).getTime(); // 转换为时间戳（毫秒）
    const endTime = new Date(endStr).getTime();

    // 校验开始时间是否晚于结束时间
    if (startTime > endTime) {
      ElMessage.error('开始时间不能晚于结束时间');
      return; // 不更新参数，保持原选择
    }

    // 计算天数差（1天 = 86400000毫秒）
    const dayDiff = (endTime - startTime) / 86400000;
    if (dayDiff > 30) {
      ElMessage.error('日期范围最长不能超过1个月');
      return; // 不更新参数，保持原选择
    }

    // 校验通过，更新参数并搜索
    searchParams.dateRange = val;
    onSearch();
  };
  const onMonthRangeChange = (val: any) => {
    // 处理清空选择的情况
    if (!val || val.length < 2) {
      searchParams.monthRange = val;
      onSearch();
      return;
    }

    const [startMonth, endMonth] = val;
    // 拆分年月（如 '2025-03' → [2025, 3]）
    const [startYear, startMonthNum] = startMonth.split('-').map(Number);
    const [endYear, endMonthNum] = endMonth.split('-').map(Number);

    // 计算月份差（跨年份需累加）
    const monthDiff = (endYear - startYear) * 12 + (endMonthNum - startMonthNum);

    // 校验开始月份是否晚于结束月份
    if (monthDiff < 0) {
      ElMessage.error('开始月份不能晚于结束月份');
      return; // 不更新参数，保持原选择
    }

    if (monthDiff > 12) {
      ElMessage.error('月份范围最长不能超过12个月');
      return; // 不更新参数，保持原选择
    }

    // 校验通过，更新参数并搜索
    searchParams.monthRange = val;
    onSearch();
  };
  const onSearch = async () => {
    const [start, end] = searchParams.dateType === '1' ? searchParams.dateRange : searchParams.monthRange;
    const params = {
      dateType: searchParams.dateType,
      startDate: start,
      endDate: end,
      lineType: searchParams.lineName,
    };
    const res = await api.getCoilSplit(params);

    // mid
    midDatax.value = ['原料重量不符原因', '质量原因', '成材率原因'];
    midData.value = [];
    midData.value.push(res.data.data.lossStatsDTO.weightLoss);
    midData.value.push(res.data.data.lossStatsDTO.qualityLoss);
    midData.value.push(res.data.data.lossStatsDTO.yieldLoss);

    // top
    bottomDatax.value = res.data.data.trackStatsResultDTO.tocDates;
    bottomWeightLoss.value = res.data.data.trackStatsResultDTO.defectWeightLossRate;
    bottomYieldLoss.value = res.data.data.trackStatsResultDTO.defectYieldLossRate;
    bottomQualityLoss.value = res.data.data.trackStatsResultDTO.defectQualityLossRate;
    bottomWeightCount.value = res.data.data.trackStatsResultDTO.defectWeightCntRate;
    bottomYieldCount.value = res.data.data.trackStatsResultDTO.defectYieldCntRate;
    bottomQualityCount.value = res.data.data.trackStatsResultDTO.defectQualityCntRate;

    const res2 = await api.getCoilCount(params);
    coilCountGraph.x = res2.data.data.tocDates;
    coilCountGraph.y1 = res2.data.data.recommendCounts;
    coilCountGraph.y2 = res2.data.data.actualCounts;
    coilCountGraph.y3 = res2.data.data.addedCosts.map((item: number) => (item < 0 ? 0 : item));
    coilCountGraph.other = res2.data.data.addedCosts;

    textLoading.value = true;
    const res3 = await api.getSummary(params);
    setTimeout(() => {
      advice.value = res3.data.data;
      adviceResult.value = res3.data.data;
      textLoading.value = false;
    }, 100);
  };

  onMounted(() => {
    resetDate();
  });

  onUnmounted(() => {
    // 销毁定时器
  });

  // 初始化时间
  const resetDate = () => {
    let start, end;
    if ('1' === searchParams.dateType) {
      start = dayjs().subtract(7, 'day').format('YYYY-MM-DD');
      end = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
      searchParams.dateRange = [start, end];
    } else {
      start = dayjs().subtract(1, 'month').format('YYYY-MM');
      end = dayjs().subtract(1, 'day').format('YYYY-MM');
      searchParams.monthRange = [start, end];
    }
    onSearch();
  };

  const formatterAdvice = (originalStr: string) => {
    let result = originalStr.replace(/^([^，]+)，/, '$1，\n');

    // 步骤2：在“卷重不符的原因有以下X点”后加换行（X为一/二/三）
    result = result.replace(/(卷重不符的原因有以下[一二三四五六七八九十]+点)/, '$1\n');

    // 步骤3：在每个原因条目（1.、2.、3.）的分号后加换行
    result = result.replace(/；(\d+\.)/g, '；\n$1');

    // 最终处理：如果最后有分号，也加换行（可选，根据格式需求）
    adviceResult.value = result.replace(/；$/, '；\n');
  };
</script>
<style lang="less" scoped>
  @import '/src/views/VolumeDivisionOptimization/deepElement.css';

  .page-layout {
    width: 100%;
    position: relative;
    min-height: 100vh;
    margin-bottom: 1vh;
    display: flex;
    flex-direction: column;
    background: url(/@/assets/images/home/body-bg.jpg) no-repeat;
    padding: 20px;
    overflow: hidden;
  }

  .tabs {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: center;
    justify-content: center;
  }

  .search {
    display: flex;
    flex-wrap: nowrap;
    position: absolute;
    right: 2vw;
    top: 2vh;
  }

  .main-container {
    display: flex;
    flex-wrap: nowrap;
    gap: 1vw;
    padding: 5px;
    height: 30vh;
    overflow: hidden;

    .item {
      height: 30vh;
      width: 50%;
    }
  }

  .radio-style {
    position: absolute;
    z-index: 99;
  }

  .top-radio-style {
    right: 2vw;
    top: 10vh;
  }

  .bottom-radio-style {
    right: 2vw;
    top: 70vh;
  }

  .advice {
    min-height: 25vh;
    border: 2px solid #3981d9;
    color: #fff;
    width: 100%;
    border-radius: 5px;
    padding: 0 0.2vw;
    display: flex;
    // text-align: center;
    align-items: center;
    justify-content: center;
  }
  // ----------------------------- element-plus样式深度穿透 -------------------------------------
  :deep(.el-divider--horizontal) {
    border-top: 1px solid #2979ff;
  }

  .time-period-picker {
    :deep(.el-date-editor) {
      min-width: 16vw;
    }
    :deep(.el-input__wrapper) {
      background: linear-gradient(90deg, #0b3571, rgba(11, 53, 113, 0) 100%);
      box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
    }
    :deep(.el-range-input) {
      color: #fff;
    }

    :deep(.el-input__wrapper.is-focus) {
      box-shadow: 0 0 0 0.06rem rgba(255, 255, 255, 0.9) inset;
    }

    :deep(.el-input__prefix) {
      color: #fff;
    }

    :deep(.el-range-separator) {
      color: #fff;
    }
  }

  :deep(.el-radio-button__inner) {
    background-color: transparent;
    color: #fff;
  }
</style>
